package com.telecom.restaurant.service;

import com.telecom.restaurant.constant.ExportExcelConstant;
import com.telecom.restaurant.dao.CouponCustomerDao;
import com.telecom.restaurant.enums.CouponCustomerStatusEnum;
import com.telecom.restaurant.model.CouponCustomerPO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by qiqi on 2019/12/14.
 */
@Service
public class CouponService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ExcelService excelService;

    @Autowired
    private CouponCustomerDao couponCustomerDao;

    public void dealExcelFile(File newFile) throws Exception {

        Workbook book = excelService.readExcel(newFile.getAbsolutePath());
        Sheet sheet = book.getSheetAt(0);
        //获得当前sheet的开始行
        int firstRowNum = 1;
        //获得当前sheet的结束行
        int lastRowNum = sheet.getLastRowNum();
        DecimalFormat df = new DecimalFormat("0");
        List<String> mobileList = new ArrayList<>(20);
        for (int rowNum = firstRowNum; rowNum <= lastRowNum; rowNum++) { //为了过滤到第一行因为我的第一行是数据库的列
            //获得当前行
            Row row = sheet.getRow(rowNum);
            if (row == null) {
                continue;
            }
            Cell cell = row.getCell(0);
            String mobile = null;
            switch (cell.getCellType()) {
                case NUMERIC: //数字
                    mobile = df.format(cell.getNumericCellValue());
                    break;
                case STRING: //字符串
                    mobile = cell.getStringCellValue();
                    break;
            }
            mobileList.add(mobile);
            if (mobileList.size() >= 20) {
                batchInsertCoupon(mobileList);
                mobileList.clear();
            }
        }
        batchInsertCoupon(mobileList);
    }

    private void batchInsertCoupon(List<String> mobiles) {
        if (CollectionUtils.isEmpty(mobiles)) {
            return;
        }
        List<CouponCustomerPO> poList = new ArrayList<>(mobiles.size());

        for (String mobile : mobiles) {
            CouponCustomerPO po = new CouponCustomerPO();
            po.setMobile(mobile);
            po.setStatus(CouponCustomerStatusEnum.AVAILABLE.getCode());
            poList.add(po);
        }

        int size = couponCustomerDao.addCouponBatch(poList);

        logger.info("batchInsertCoupon success size:{}", size);
    }

    public void exportCouponList(Long restaurantId, OutputStream out) throws Exception {
        try {
            // 第一步，创建一个workbook，对应一个Excel文件
            HSSFWorkbook workbook = new HSSFWorkbook();

            // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet hssfSheet = workbook.createSheet("sheet1");

            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = hssfSheet.createRow(0);

            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle commonStyle = workbook.createCellStyle();
            commonStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中

            HSSFCell hssfCell = null;
            for (int i = 0; i < ExportExcelConstant.COUPON_LIST_TITLE.length; i++) {
                hssfCell = row.createCell(i);//列索引从0开始
                hssfCell.setCellStyle(commonStyle);
                hssfCell.setCellValue(ExportExcelConstant.COUPON_LIST_TITLE[i]);//列名1
            }

            // 第五步，写入数据
            // 查询订单
            int offset = 0;
            int limit = 100;
            int rowIndex = 1;
            while (true) {
                List<String> mobileList = couponCustomerDao.getAllMobiles(offset, limit, 1);
                if (mobileList == null || mobileList.isEmpty()) {
                    break;
                }
                for (String mobile : mobileList) {
                    row = hssfSheet.createRow(rowIndex++);
                    hssfCell = row.createCell(0);
                    hssfCell.setCellStyle(commonStyle);
                    hssfCell.setCellValue(mobile);
                }
                if (mobileList.size() < limit) {
                    break;
                }
            }

            hssfSheet.setColumnWidth(0, 3200);

            // 第七步，将文件输出到客户端浏览器
            try {
                workbook.write(out);
                out.flush();
                out.close();

            } catch (Exception e) {
                logger.error("exprt file error. restaurantId:{}", restaurantId, e);
            }
        } catch (Exception e) {
            logger.error("exprt file error. restaurantId:{}", restaurantId, e);
            throw new Exception("导出信息失败！");

        }
    }

}
